// 强制所有请求走Charles，即使系统代理未设置  HttpOverrides.global = NoProxyHttpOverrides();
import 'dart:async';
import 'dart:io';

import 'package:dio/dio.dart';
import 'package:dio/io.dart';
import 'package:flutter_common_utils/common_utils_export.dart';

class HttpProxy {
  HttpProxy._();

  static const String proxySpKey = "proxy";

  // static String textAddress = "192.168.137.234:8888";
  static String textAddress = "";

  static get httpProxyAddress => textAddress.isNotEmpty ? textAddress : proxySpKey.getStore();

  //1 修改dio代理，2:修改全局代理
  static int type = 2;

  /// 创建代理
  static void startSet(Dio dio) {
    if (type == 1) {
      if (httpProxyAddress.length > 10) {
        (dio.httpClientAdapter as IOHttpClientAdapter).createHttpClient = () {
          final HttpClient client = HttpClient();
          client.findProxy = (Uri uri) {
            // 返回代理服务器地址
            return "PROXY $httpProxyAddress";
            // return "PROXY 192.168.137.234:8888";
          };
          client.badCertificateCallback = (X509Certificate cert, String host, int port) => true; // 忽略 SSL 证书验证
          return client;
        };
      }
    } else {
      if (httpProxyAddress.length > 10) {
        HttpOverrides.global = _NoProxyHttpOverrides();
      } else {
        HttpOverrides.global = null;
      }
    }
  }

  // 获取本机IP和子网掩码（需适配不同平台）
  static Future<String> _getLocalNetwork() async {
    final interfaces = await NetworkInterface.list();
    print("interfaces: $interfaces");
    for (var interface in interfaces) {
      if (interface.name.startsWith("wlan")) {
        for (var addr in interface.addresses) {
          if (addr.type == InternetAddressType.IPv4 && !addr.isLoopback) {
            return addr.address;
          }
        }
      }
    }
    return "";
  }

  //生成待扫描的IP列表
  static List<String> _generateIPList(String baseIP) {
    if (baseIP.isEmpty) return [];
    final ipParts = baseIP.split('.');
    // final start = int.parse(ipParts[3]);
    final total = 255 - 2; // 示例：扫描整个子网
    return List.generate(total, (i) => '${ipParts[0]}.${ipParts[1]}.${ipParts[2]}.${i + 2}');
  }

  //并行扫描 8888 端口
  static Future<List<String>> _scanCharlesIP(List<String> ips, {int port = 8888}) async {
    final completer = Completer<List<String>>();
    final result = <String>[];
    var completed = 0;

    for (var ip in ips) {
      Socket.connect(ip, port, timeout: Duration(seconds: 1))
          .then((socket) {
            result.add(ip);
            socket.destroy();
          })
          .catchError((_) {})
          .whenComplete(
            () {
              completed++;
              if (completed == ips.length && !completer.isCompleted) {
                completer.complete(result);
              }
            },
          );
    }

    return completer.future;
  }

  //获取本地局域网 Charles 代理
  static Future<List<String>> getLocalCharlesProxy({int port = 8888}) async {
    final network = await _getLocalNetwork();
    print("Local Network: $network");
    final ips = _generateIPList(network);
    print("Scanning IPs: $ips");
    final charlesIP = await _scanCharlesIP(ips, port: port);
    if (charlesIP.isNotEmpty) {
      print("Found Charles at: $charlesIP");
    } else {
      print("Charles not found in LAN.");
    }
    return charlesIP;
  }
}

//设置后会修改应用所有使用 HttpClient 的请求（包括第三方库）。
class _NoProxyHttpOverrides extends HttpOverrides {
  @override
  HttpClient createHttpClient(SecurityContext? context) {
    final HttpClient client = super.createHttpClient(context);
    client.findProxy = (Uri uri) {
      // 返回代理服务器地址
      return "PROXY ${HttpProxy.httpProxyAddress}";
    };
    client.badCertificateCallback = (X509Certificate cert, String host, int port) => true; // 忽略 SSL 证书验证
    return client;
  }
}
